# -*- coding:utf-8 -*-
from __future__ import absolute_import, unicode_literals

from celery import shared_task
from utils.tools import *
# from utils.tools import registry_wb_company_info, registry_wb_person_info, registry_bind_lift_person_info, \
#     registry_wb_contract_info

from utils.logger import get_logger
from users.models import CompanyInfo, Person
from basic.models import ElevatorInfo, ElevatorPersonInfo, ElevatorStatistics, ElevatorYearStatistics
from maintenance.models import Contract, Task
from utils.response import ErrorCode
import datetime
import json
from .settings import ANOTHER_REGISTRY
from manufacturer.call_interface import do_beat, elevator_status, elevator_statistics, device_statistics, elevator_online_numbers
from utils.piccode import add_time_to_picture
import os
import redis
from manufacturer.models import ElevatorFault, AlarmMsg


logger = get_logger(__name__)


@shared_task
def test_for_celery(model_name, model_id):
    print model_name
    if model_name == 'CompanyInfo':
        registry_wb_company_info(CompanyInfo, model_id)
        if ANOTHER_REGISTRY:
            another_update_company(CompanyInfo, model_id)
    elif model_name == 'Person':
        registry_wb_person_info(Person, model_id)
        if ANOTHER_REGISTRY:
            another_update_person(Person, model_id)
    elif model_name == 'ElevatorInfo':
        registry_bind_lift_person_info(ElevatorInfo, model_id)
    elif model_name == 'Contract':
        registry_wb_contract_info(Contract, model_id)
    # elif model_name == 'ElevatorPersonInfo':
    #     registry_elevator_person_info(ElevatorPersonInfo, model_id)
    elif model_name == 'ElevatorInfoDelete':
        pass
    elif model_name == 'Task':
        if ANOTHER_REGISTRY:
            another_update_maintain_record(Task, model_id)
    else:
        pass
    return 'celery is over!'


def get_base_number(number):
    if number % 40 == 0:
        return number - 40
    else:
        return number - number % 40


@shared_task
def auto_add_periodic_task():
    # logger.info(u"开始执行工单自动创建")
    u""" 以第一次创建的工单日期为原点，根据电梯的维保周期创建工单，在第三个月点上创建季单,六个月点上创建半年单,9个月上创建季单， 12个月
    点上创建年单，每次只创建一次，如果有修改不再创建，bug：如果年单到了，但修改为其他工单，那么之后所有的都是半月单，必须创建一个年单
    作为原点"""
    print u'自动更新周期任务'
    now = datetime.datetime.now()
    today = datetime.datetime(year=now.year, month=now.month, day=now.day)
    fifteen_days_later = today + datetime.timedelta(days=15)
    elevators = Task.objects.filter_active(flag=True, elevator__registry_status=20,
                                           elevator__usage_status=10).values_list('elevator', flat=True).distinct()
    i = 0
    for elevator in elevators:
        try:
            task = Task.objects.filter_active(elevator=elevator).order_by('-id').first()
            if task.status not in (30, 40, 80):
                continue
            task_0 = Task.objects.filter_active(elevator=elevator, flag=True).order_by('-id').first()
            elevator = ElevatorInfo.objects.filter_active(id=elevator).first()
            pre_obj = Task.objects.order_by('-id').first()
            if task:
                # task_day = task.day
                # task_day = datetime.datetime.combine(task_day, datetime.time())
                task_day = task.task_end_time
                task_0_day = task_0.day
                task_0_day = datetime.datetime.combine(task_0_day, datetime.time())

                if task_day + datetime.timedelta(days=elevator.elevator_cycle) <= fifteen_days_later:

                    t = datetime.datetime.now().strftime("%Y-%m-%d")
                    t = "".join(t.split("-")).decode()
                    s_t = u"BYGD" + t
                    if pre_obj and pre_obj.sn.startswith(s_t):
                        pre_tail = pre_obj.sn.split(s_t)[1]
                        pre_tail = int(pre_tail)
                        tail = pre_tail + 1
                        tail = unicode(tail).rjust(6, u'0')
                        sn = s_t + tail
                    else:
                        sn = s_t + u'000001'

                    worker = ElevatorPersonInfo.objects.filter(worker_type=10, elevator=elevator).\
                        values_list('worker', flat=True).distinct()
                    worker = list(worker)
                    worker = json.dumps(worker)
                    # day = fifteen_days_later
                    day = task_day + datetime.timedelta(days=elevator.elevator_cycle)
                    if task_day < task_0_day + datetime.timedelta(days=365) <= day:
                        maintain_type = get_base_number(task.maintain_type) + 10
                        flag = True
                    elif task_day < task_0_day + datetime.timedelta(days=273) <= day:
                        maintain_type = get_base_number(task.maintain_type) + 20
                        flag = False
                    elif task_day < task_0_day + datetime.timedelta(days=182) <= day:
                        maintain_type = get_base_number(task.maintain_type) + 40
                        flag = False
                    elif task_day < task_0_day + datetime.timedelta(days=91) <= day:
                        maintain_type = get_base_number(task.maintain_type) + 20
                        flag = False
                    else:
                        maintain_type = get_base_number(task.maintain_type) + 30
                        flag = False
                    contract = elevator.contract
                    c_start_time = contract.start_time[:10]
                    start_time = datetime.datetime.strptime(c_start_time, "%Y-%m-%d") if u"-" in c_start_time else \
                        datetime.datetime.strptime(c_start_time, "%Y/%m/%d")
                    c_end_time = contract.end_time[:10]
                    end_time = datetime.datetime.strptime(c_end_time, "%Y-%m-%d") if u"-" in c_end_time else \
                        datetime.datetime.strptime(c_end_time, "%Y/%m/%d")
                    if start_time <= today <= end_time and start_time <= day <= end_time:
                        service_id = task.service_id
                        update_by = task.update_by
                        Task.objects.create(sn=sn, day=day, worker=worker, elevator=elevator, maintain_type=maintain_type,
                                            flag=flag, service_id=service_id, update_by=update_by, is_first=False)
                        i += 1
                        print u'开始自动创建'
                    else:
                        logger.info("电梯合同过期了: %s" % elevator.id)

        except Exception as e:
            logger.info(e)
    logger.info("今日共创建工单 %s 个" % i)


@shared_task
def auto_add_elevator_statistics():
    today = datetime.date.today()
    companys = CompanyInfo.objects.filter_active(company_type=100)
    for company in companys:
        num = company.maintain_company_elevator_info.filter_active().count()
        update_by = company.company_person.filter_active(is_admin=True).first().auth_user.id
        ElevatorStatistics.objects.get_or_create(company=company, day=today, defaults={'numbers': num,
                                                 'service_id': company.id, 'update_by': update_by})


@shared_task
def push_by_alias(user_id, msg):
    from ElevatorAdmin.settings import JG_AppKey as app_key
    from ElevatorAdmin.settings import JG_Master_Secret as master_secret
    from utils import jpush
    _jpush = jpush.JPush(app_key, master_secret)
    _jpush.set_logging("DEBUG")
    push = _jpush.create_push()
    alias = ['alias' + user_id]
    alias1 = {"alias": alias}
    logger.info(alias1)
    push.audience = jpush.audience(
        alias1
    )

    push.notification = jpush.notification(alert=msg)
    push.platform = jpush.all_
    print (push.payload)
    push.send()


@shared_task
def submit(task_id, estate=False):
    logger.info(u"submit-----come------")
    task = Task.objects.filter_active(id=task_id).first()
    dics = json.loads(task.result)['extra']
    for dic in dics:
        if dic.get("need_add_time", None):
            p = dic['image']
            l = "../media/" + os.path.basename(p)
            add_time_to_picture(l)
            print u"打码完毕 %s" % task_id
    company = task.elevator.maintain_company
    if not company.link_account and not company.link_token:
        task.status = 30
        if estate:
            task.status = 40
        task.save(update_fields=['status'])
        return
    person = Person.objects.get(id=task.maintainer_id)
    user = person.auth_user
    f_code = first_maintain_registry(company.link_account, company.link_token, task_id, person)
    if f_code != ErrorCode.SUCCESS:
        return

    et_code = end_task(company.link_account, company.link_token, task_id, user.sign_image, task.result, person)
    if et_code != ErrorCode.SUCCESS:
        return

    task.status = 80
    task.save(update_fields=['status'])
    if estate:
        e_code = estate_confirm_registry(company.link_account, company.link_token, task_id, task.signature, task.estate_confirm)
        if e_code != ErrorCode.SUCCESS:
            return
        task.status = 40
        task.save(update_fields=['status'])


@shared_task
def manual_submission(task_ids):
    logger.info(u"manual_submit-----come------")
    for task_id in task_ids:
        task = Task.objects.filter_active(id=task_id).first()
        if not task:
            continue
        if task.status not in (110, 120, 130, 140, 90):
            continue
        company = task.elevator.maintain_company
        person = Person.objects.get(id=task.maintainer_id)
        user = person.auth_user
        b = True if task.estate_confirm else False
        if task.status in (110, 120, 130):
            f_code = first_maintain_registry(company.link_account, company.link_token, task_id, person)
            if f_code != ErrorCode.SUCCESS:
                continue
            et_code = end_task(company.link_account, company.link_token, task_id, user.sign_image, task.result, person)
            if et_code != ErrorCode.SUCCESS:
                continue
            task.status = 80
            task.save(update_fields=['status'])
            if b:
                e_code = estate_confirm_registry(company.link_account, company.link_token, task_id, task.signature, task.estate_confirm)
                if e_code != ErrorCode.SUCCESS:
                    continue
                task.status = 40
                task.save(update_fields=['status'])

        elif task.status == 140:
            et_code = end_task(company.link_account, company.link_token, task_id, user.sign_image, task.result, person)
            if et_code != ErrorCode.SUCCESS:
                continue
            task.status = 80
            task.save(update_fields=['status'])
            if b:
                e_code = estate_confirm_registry(company.link_account, company.link_token, task_id, task.signature,
                                                 task.estate_confirm)
                if e_code != ErrorCode.SUCCESS:
                    continue
                task.status = 40
                task.save(update_fields=['status'])
        elif task.status == 90:
            if b:
                e_code = estate_confirm_registry(company.link_account, company.link_token, task_id, task.signature,
                                                 task.estate_confirm)
                if e_code != ErrorCode.SUCCESS:
                    continue
                task.status = 40
                task.save(update_fields=['status'])


@shared_task
def do_beat_for_register():
    from ElevatorAdmin.settings import TO_GOV
    if not TO_GOV:
        return
    # TODO
    do_beat()


@shared_task
def status_for_register(obj_id):
    # TODO
    elevator_status(obj_id)


@shared_task
def statistics_for_register():
    # TODO
    elevator_statistics(),
    # device_status()
    device_statistics()
    elevator_online_numbers()


@shared_task
def data_sync(task_id):
    t = Task.objects.filter(id=task_id)
    r = redis.Redis(host='47.99.78.237', port=6379, db=3)
    if t:
        # r.lpush("task", t.to_json())
        print u"要插入redis了 %s " % task_id


@shared_task
def statistics_for_authority_code_update():
    from manufacturer.models import AuthorityCode
    acs = AuthorityCode.objects.filter_active()
    for ac in acs:
        ac.yesterday_bend_times = ac.bend_times
        ac.yesterday_run_times = ac.run_times
        ac.yesterday_open_times = ac.open_times
        ac.yesterday_up_time = ac.up_time
        ac.save()


@shared_task
def update_elevator_fault_status():
    five_min_ago = datetime.datetime.now() - datetime.timedelta(minutes=5)
    ten_min_ago = datetime.datetime.now() - datetime.timedelta(minutes=10)
    # 前10-5分钟的数据
    alarms = AlarmMsg.objects.filter_active(update_time__gte=ten_min_ago, update_time__lt=five_min_ago).values_list("id", flat=True).distinct()
    ElevatorFault.objects.filter_active(alarm_id__in=alarms).update(s='c')


@shared_task
def cal_elevator_number_for_every_year():
    service_ids = ElevatorInfo.objects.filter_active().values_list("service_id", flat=True).distinct()
    for service_id in service_ids:
        today = datetime.datetime.today()
        eis = ElevatorInfo.objects.filter_active(service_id=service_id)
        if not eis:
            continue
        mi = ""
        dic = dict()
        ma = datetime.datetime(year=today.year, month=1, day=1)
        for i in eis:
            if i.register_code:
                try:
                    k = i.register_code[10: 14]
                    year = datetime.datetime.strptime(k, '%Y')
                    if year >= datetime.datetime(year=1949, month=1, day=1):
                        if not mi:
                            mi = year
                        if year < mi:
                            mi = year
                        if k not in dic:
                            dic[k] = 0
                        dic[k] += 1
                except:
                    pass
        if not mi:
            continue
        next_year = mi
        sums = 0
        while next_year <= ma:
            k = next_year.strftime('%Y')
            if k not in dic:
                dic[k] = 0
            dic[k] += sums
            sums = dic[k]
            next_year = datetime.datetime(year=next_year.year + 1, month=1, day=1)
        ElevatorYearStatistics.objects.filter_active(service_id=service_id).exclude(year__in=dic.keys()).update(is_active=False)
        for i in dic:
            ElevatorYearStatistics.objects.update_or_create(service_id=service_id, year=i, defaults={"number": dic[i], "is_active": True})






















